package com.example.competionmanagebackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.competionmanagebackend.entity.Users;
import com.example.competionmanagebackend.service.UsersService;
import com.example.competionmanagebackend.utils.JwtUtil;
import com.example.competionmanagebackend.utils.PageRequest;
import com.example.competionmanagebackend.utils.PageResult;
import com.example.competionmanagebackend.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Resource
    private UsersService usersService;

    @PostMapping("/login")
    public ResponseEntity<Result<String>> login(@RequestBody Users loginUser) {
        Users user = usersService.login(loginUser.getUserName(), loginUser.getPassword());
        if (user != null) {
            String token = JwtUtil.generateToken(user.getUserName());
            return Result.success(token);
        } else {
            return Result.fail(401, "账户或密码错误");
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Result<String>> register(@RequestBody Users registerUser) {
        if (registerUser.getUserName() == null || registerUser.getUserName().trim().isEmpty()) {
            return Result.fail(400, "Username cannot be empty");
        }
        if (registerUser.getPassword() == null || registerUser.getPassword().trim().isEmpty()) {
            return Result.fail(400, "Password cannot be empty");
        }

        Users existingUser = usersService.getUserByUsername(registerUser.getUserName());
        if (existingUser != null) {
            return Result.fail(409, "Username already exists");
        }

        registerUser.setCreatedAt(new Date());
        registerUser.setUpdatedAt(new Date());
        if (registerUser.getRole() == null) {
            registerUser.setRole(2);
        }

        try {
            usersService.insertUser(registerUser);
            String token = JwtUtil.generateToken(registerUser.getUserName());
            return Result.success(token);
        } catch (Exception e) {
            return Result.fail(500, "Registration failed: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息。
     * 全局 Token 拦截器已验证 token，并将用户名存入请求属性 "username"。
     */
    @GetMapping("/info")
    public ResponseEntity<Result<Users>> getInfo(HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        if (username == null) {
            return Result.fail(401, "Token is missing or invalid");
        }
        Users user = usersService.getUserByUsername(username);
        if (user != null) {
            user.setPassword(null); // 去除敏感信息
            return Result.success(user);
        } else {
            return Result.fail(404, "User not found");
        }
    }

    @PostMapping("/getUsersPage")
    public ResponseEntity<Result<PageResult<Users>>> getUsersPage(@RequestBody PageRequest pageRequest) {
        Page<Users> page = usersService.getUsersPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        PageResult<Users> result = new PageResult<>(page);
        return Result.success(result);
    }

    /**
     * 新增/修改用户接口
     * 仅允许经过全局拦截器验证的用户访问。
     */
    @PostMapping("/edit")
    public ResponseEntity<Result<Users>> editUser(@RequestBody Users user, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        if (username == null) {
            return Result.fail(401, "Token is missing or invalid");
        }
        // 业务上可根据 username 判断是否具备修改权限，此处简单处理
        if (user.getId() == null) {
            usersService.insertUser(user);
        } else {
            usersService.updateUser(user);
        }
        return Result.success(user);
    }

    /**
     * 删除用户接口。
     */
    @GetMapping("/delete")
    public ResponseEntity<Result<String>> deleteUser(@RequestParam("id") Integer id, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        if (username == null) {
            return Result.fail(401, "Token is missing or invalid");
        }
        // 如有需要可添加更详细的权限校验
        usersService.deleteUser(id);
        return Result.success("删除成功");
    }
}
